import React, {useState} from "react";
import {Button, Checkbox, CheckboxProps, Form, Input, Space,message as antdMessage} from "antd";
import FormItem from "antd/es/form/FormItem";
import Link from "antd/es/typography/Link";
import {comPlatReq, openLoginModal} from "../ComReq";
import {setUserInfoToLocal, setUserTokenToLocal} from "../utils/LocalStorageUtils";
import {PlatReq, UserResp} from "../types/CommonTypes";

type PhoneLoginFormProps = {
    onFinish: () => void;
}

const PhoneLoginForm:React.FC<PhoneLoginFormProps> = ({onFinish})=>{
    const [formRef] = Form.useForm();
    const [checked, setChecked] = useState(false);
    const [sendSmsCodeBtnAllow, setSendSmsCodeBtnAllow] = useState(false);
    const [sendSmsCodeBtnText, setSendSmsCodeBtnText] = useState("发送验证码");
    const [sequenceNum, setSequenceNum] = useState("");
    const onChangeCheckedAgreement:CheckboxProps["onChange"] =(e) =>{
        setChecked(e.target.checked)
    }
    const onSubmit =()=>{
        formRef.validateFields();
        const fieldsValue = formRef.getFieldsValue();
        const loginName = fieldsValue.loginName;
        if (!loginName){
            return;
        }
        const smsCode = fieldsValue.smsCode;
        if (!smsCode){
            return;
        }
        const checkedAgreement = fieldsValue.checkedAgreement;
        if (!checkedAgreement){
            return;
        }
        const req: PlatReq ={
            interfaceName: "smsCodeLogin",
            reqData: {sequenceNum:sequenceNum,...fieldsValue},
        }
        comPlatReq(req)
            .then((data)=>{
                const res = data as Record<string, UserResp>;
                const result = res.result;
                //缓存登陆信息
                setUserTokenToLocal(result.token,result.expire);
                setUserInfoToLocal(result.userBean,result.expire);
                onFinish();
            }).catch(err=>{
                if (err!=openLoginModal) {
                    antdMessage.error(err);
                }
            });
    }
    /**
     * 离开手机号输入框发起验证
     */
    const handlePhoneBlur = () => {
        const loginName = formRef.getFieldValue("loginName");
        const phoneRegex = /^1[3-9]\d{9}$/;
        if (!phoneRegex.test(loginName)) {
            antdMessage.error("手机号不正确")
        }
        if (loginName) {
            setSendSmsCodeBtnAllow(true);
        } else {
            setSendSmsCodeBtnAllow(false);
        }
    };
    /**
     * 发送验证码
     */
    const sendSmsCode=()=>{
        const loginName = formRef.getFieldValue("loginName");
        if (!loginName) {
            antdMessage.error("请输入手机号");
            return;
        }
        const req: PlatReq ={
            interfaceName: "sendLoginSmsCode",
            reqData: { phone:  loginName},
        }
        comPlatReq(req)
            .then((data)=>{
                const res = data as Record<string, Record<string, string>>;
                setSequenceNum(res.result.sequenceNum)
                formRef.setFieldsValue({sequenceNum:sequenceNum});
                let surplus = 60;
                const interval = setInterval(() => {
                    if (surplus <= 0) {
                        clearInterval(interval);
                        setSendSmsCodeBtnText("发送验证码");
                        setSendSmsCodeBtnAllow(true);
                    } else {
                        surplus--;
                        setSendSmsCodeBtnText(surplus + "秒后可再次发送");
                        setSendSmsCodeBtnAllow(false);
                    }
                }, 1000);
            }).catch(err=>{
            antdMessage.error(err);
        });
    }
    return (<>
        <Form form={formRef} layout="horizontal">
            <FormItem name="loginName" label="手机号"
                      rules={[{ required: true,message:"手机号必填" },
                          { pattern: /^1[3-9]\d{9}$/,message:"手机号格式不对" }]}>
                <Input name="loginName" placeholder="请输入手机号" size="large" onBlur={handlePhoneBlur} />
            </FormItem>
            <FormItem name="smsCode" label="验证码" rules={[{ required: true,message:"验证码必填" },
                { pattern: /^\d{6}$/,message:"验证码格式不对" }]}>
                <Space.Compact style={{ width: '100%' }}>
                    <Input name="smsCheckCode" placeholder="请输入验证码"  size="large"/>
                    <Button size="large" onClick={sendSmsCode} disabled={!sendSmsCodeBtnAllow}>
                        {sendSmsCodeBtnText}
                    </Button>
                </Space.Compact>
            </FormItem>
            <FormItem name="checkedAgreement" valuePropName="checked"
                      rules={[
                          {
                              validator: (_, value) => {
                                  if (value) {
                                      return Promise.resolve();
                                  }
                                  return Promise.reject(new Error('请同意协议！'));
                              },
                          }]}>
                <Checkbox name="checkedAgreement" checked={checked} onChange={onChangeCheckedAgreement}>
                    未注册的手机号验证后自动注册并登陆，且代表您已同意<Link>用户服务协议</Link>
                </Checkbox>
            </FormItem>
            <FormItem>
                <Button type="primary" style={{width:'100%'}} size="large" onClick={onSubmit}>登陆</Button>
            </FormItem>
        </Form>
    </>);
}

export default PhoneLoginForm;